package com.security.web.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 能拿到Http的请求和响应,能拿到是那个控制器、方法来处理的信息
 * 不能拿到执行方法的值
 *
 * @author roger
 * @email 190642964@qq.com
 * @create 2017-11-01 17:22
 **/
@Component
public class TimeInterceptor implements HandlerInterceptor {

    /**
     * 在Controller方法之前调用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("preHandle");

        System.out.println(((HandlerMethod) handler).getBean().getClass().getName());
        System.out.println(((HandlerMethod) handler).getMethod().getName());

        request.setAttribute("startTime", System.currentTimeMillis());
        // 不向下执行，也就是不再调用Controller中的方法
//        return false;
        return true;
    }

    /**
     * 在Controller方法之后调用，抛出异常不执行该方法
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
        long start = (long) request.getAttribute("startTime");
        long finish = System.currentTimeMillis();
        System.out.println("time interceptor 耗时 : " + (finish - start));
    }

    /**
     * 在Controller方法之后调用，抛出异常也执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion");
        long start = (long) request.getAttribute("startTime");
        long finish = System.currentTimeMillis();
        System.out.println("time interceptor 耗时 : " + (finish - start));
        System.out.println("exception is : " + e);
    }
}
